package com.linked.store.util;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import javax.swing.filechooser.FileSystemView;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Hashtable;

/**
 * @author :dbq
 * @date : 2023/1/29 13:53
 * @description : desc
 */
public class QRBarCodeUtil {
    public static final int CODE_WIDTH = 400;
    public static final int CODE_HEIGHT = 400;
    public static final int FRONT_COLOR = 0x000000;
    public static final int BACKGROUND_COLOR = 0xFFFFFF;

    public static void main(String[] args) throws IOException, WriterException {
        String codeContent1 = "002";
        createCodeToFile(codeContent1, null, null);
    }

    public static void createCodeToFile(String codeContent, File codeImgFileSaveDir, String fileName) throws IOException, WriterException {
        if (codeContent == null || codeContent.trim().equals("")) {
            return;
        }
        codeContent = codeContent.trim();
        // 获取桌面路径
        if (codeImgFileSaveDir == null) {
            codeImgFileSaveDir = FileSystemView.getFileSystemView().getHomeDirectory();
        }


        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss");
        String time = formatter.format(LocalDateTime.now());
//        fileName = "waterkid" + time + ".png ";

        // hints 提示
        HashMap<EncodeHintType, Object> hints = new HashMap<>();
        // 字符编码类型
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        // 设置误差校正
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        // 设置二维码边距，，单位像素，值越小，二维码距离四周越近
        hints.put(EncodeHintType.MARGIN, 1);


        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        // MultiFormatWriter.encode() ：将内容写成 矩阵
        BitMatrix bitMatrix = multiFormatWriter.encode(codeContent, BarcodeFormat.QR_CODE, CODE_WIDTH, CODE_HEIGHT, hints);

        BufferedImage bufferedImage = new BufferedImage(CODE_WIDTH, CODE_HEIGHT, BufferedImage.TYPE_INT_BGR);

        for (int i = 0; i < CODE_WIDTH; i++) {
            for (int j = 0; j < CODE_HEIGHT; j++) {
                bufferedImage.setRGB(i, j, bitMatrix.get(i, j) ? FRONT_COLOR : BACKGROUND_COLOR);
            }
        }

        // 保存图片
        File codeImgFile = new File(codeImgFileSaveDir, fileName);
        ImageIO.write(bufferedImage, "png", codeImgFile);

        //System.out.println("二维码生成成功： " + codeImgFile.getPath());
    }


    public static String parseQRCodeByFile(File file) throws NotFoundException, IOException {
        String resultStr = null;
        if (file == null || file.isDirectory() || !file.exists()) {
            return resultStr;
        }

        BufferedImage bufferedImage = ImageIO.read(file);

        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
        // BinaryBitmap:二进制位图   HybridBinarizer 用于读取二维码图像数据
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

        Hashtable hints = new Hashtable<>();
        hints.put(DecodeHintType.CHARACTER_SET, "utf-8");

        // MultiFormatReader 的 decode ： 读取位图数据
        com.google.zxing.Result result = new MultiFormatReader().decode(bitmap, hints);
        resultStr = result.getText();

        return resultStr;
    }


    public void test01() throws NotFoundException, IOException {
        String imgUrl = FileSystemView.getFileSystemView().getHomeDirectory() + File.separator + "222.png";
        System.out.println(parseQRCodeByFile(new File(imgUrl)));
    }

}
